import {
  login,
  logout,
  getInfo
} from '@/api/user'
import {
  getList as getMenuList
} from '@/api/system/menu'
import {
  getUserRoleAuthority,
  GetUserBtns
} from '@/api/system/user-role'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import Cookies from 'js-cookie'
import router, {
  resetRouter
} from '@/router'

const state = {
  token: getToken(),
  id: Cookies.get('user-id') || '',
  userInfo: null,
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  menus: [],
  permissions: [],
  userBtns: [],
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ID: (state, id) => {
    Cookies.set('user-id', id)
    state.id = id
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_MENUS: (state, data) => {
    state.menus = data
  },
  SET_PERMISSION: (state, data) => {
    state.permissions = data
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_BTNS: (state, btns) => {
    state.userBtns = btns
  },
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {

    const {
      // LoginUserName,
      // LoginUserPwd,
      // Platform
      username,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        loginUserName: username.trim(),
        loginUserPwd: password,
        platform: 'PC'
        // Platform
      }).then(response => {
        const {
          data
        } = response
        commit('SET_TOKEN', data.Token)
        commit('SET_ID', data.Id)
        setToken(data.Token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo({
        Id: state.id
      }).then(response => {
        const {
          data
        } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const {
          // roles,
          name,
          avatar,
          introduction
        } = data

        // roles must be a non-empty array
        // if (!roles || roles.length <= 0) {
        //   reject('getInfo: roles must be a non-null array!')
        // }
        const roles = ['admin']
        commit('SET_ROLES', roles)
        data.roles = roles
        // commit('SET_NAME', name)
        // commit('SET_AVATAR', avatar)
        // commit('SET_INTRODUCTION', introduction)
        // commit('SET_ROLES', [])
        commit('SET_USER_INFO', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getMenus({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getMenuList({
        PlatFormType: 'PC',
        MenuName: "", //页面名称
        IsPaging: false, //是否分页
        SortName: "MenuSort", //排序栏位
        SortType: true //排序类型｛True：正序；Flase：反序｝
      }).then(response => {
        const {
          data
        } = response
        commit('SET_MENUS', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getPermissions({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getUserRoleAuthority({
        RoleId: state.userInfo.RoleId,
        PlatForm: 'PC'
      }).then(response => {
        const {
          data
        } = response
        commit('SET_PERMISSION', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getRoleButtons({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      GetUserBtns({
        RoleId: state.userInfo.RoleId
      }).then(res => {
        if (res.Data && res.Data.length > 0) {
          let btns = res.Data.map(item => {
            return item.BtnCode
          })
          commit('SET_BTNS', btns)
          resolve()
        }
        resolve()
      }).catch(err => {
        reject(err)
      })


    })
  },
  // user logout
  logout({
    commit,
    state,
    dispatch
  }) {
    return new Promise((resolve, reject) => {
      logout({
        Id: state.id,
        Platform: 'PC',
      }).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ID', '')
        commit('SET_USER_INFO', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        dispatch('permission/cleanRoute', null, {
          root: true
        })
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, {
          root: true
        })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({
    commit,
    dispatch
  }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const {
      roles
    } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, {
      root: true
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
